<template>
  <div>
    <div class="toolbar">
      <el-button type="primary" @click="handleAddPosition">添加职位</el-button>
    </div>

    <el-table :data="positions" style="width: 100%" border>
      <el-table-column prop="id" label="ID" width="60" />
      <el-table-column prop="name" label="职位名称" width="120" />
      <el-table-column prop="memberType" label="职位类型" width="120">
        <template #default="scope">
          {{ {
            'A': '文史会员',
            'B': '联盟成员',
            'C': '联盟企业'
          }[scope.row.memberType] }}
        </template>
      </el-table-column>
      <el-table-column prop="level" label="职位等级" width="100" align="center" />
      <el-table-column prop="description" label="职位描述" />
      <el-table-column prop="fee" label="会费金额" width="100">
        <template #default="scope">
          {{ scope.row.fee > 0 ? `${scope.row.fee} 元` : '免费' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="handleEditPosition(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDeletePosition(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 职位编辑对话框 -->
    <el-dialog v-model="positionDialogVisible" :title="positionForm.id ? '编辑职位' : '添加职位'" width="500px" top="8vh"
      append-to-body>
      <el-form :model="positionForm" label-width="100px">
        <el-form-item label="职位类型">
          <el-select v-model="positionForm.memberType" placeholder="请选择职位类型">
            <el-option label="文史会员" value="A" />
            <el-option label="联盟成员" value="B" />
            <el-option label="联盟企业" value="C" />
          </el-select>
        </el-form-item>
        <el-form-item label="职位名称">
          <el-input v-model="positionForm.name" />
        </el-form-item>
        <el-form-item label="职位等级">
          <el-input-number v-model="positionForm.level" :min="1" :max="10" />
        </el-form-item>
        <el-form-item label="会费金额">
          <el-input-number v-model="positionForm.fee" :min="0" :step="100" />
          <span class="form-tip">设置为0表示免费</span>
        </el-form-item>
        <el-form-item label="职位描述">
          <el-input v-model="positionForm.description" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="positionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePosition">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import PositionAPI from "@/api/position/position"

const props = defineProps({
  members: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:positions'])

// 职位管理
const positions = ref([])
const positionDialogVisible = ref(false)
const positionForm = ref({
  id: null,
  name: '',
  level: 1,
  description: '',
  fee: 0,
  memberType: 'A' // 默认为A类（文史会员）
})

// 获取职位列表
const getPositionList = async () => {
  try {
    const response = await PositionAPI.getPage()
    console.log(response.list);
    positions.value = response.list || []
    emit('update:positions', positions.value)
  } catch (error) {
    console.error('获取职位列表失败：', error)
    ElMessage.error('获取职位列表失败')
  }
}

// 职位管理方法
const handleAddPosition = () => {
  positionForm.value = {
    id: null,
    name: '',
    level: 1,
    description: '',
    fee: 0,
    memberType: 'A' // 默认为A类（文史会员）
  }
  positionDialogVisible.value = true
}

const handleEditPosition = (row) => {
  positionForm.value = { ...row }
  positionDialogVisible.value = true
}

// 删除职位
const handleDeletePosition = (row) => {
  // 检查是否有会员使用该职位
  const usedByMembers = props.members.some(member => member.position === row.name)

  if (usedByMembers) {
    ElMessage.warning(`该职位正在被会员使用，无法删除`)
    return
  }

  ElMessageBox.confirm(
    `确定要删除职位 ${row.name} 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await PositionAPI.deleteByIds(row.id)
      getPositionList()
      ElMessage.success('删除成功')
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => { })
}

// 编辑职务保持
const savePosition = async () => {
  if (!positionForm.value.name) {
    ElMessage.warning('请输入职位名称')
    return
  }
  try {
    if (positionForm.value.id) {
      // 编辑现有职位
      await PositionAPI.update(positionForm.value.id, positionForm.value)
      ElMessage.success('更新成功')
      getPositionList()
    } else {
      // 添加新职位
      await PositionAPI.addPosition(positionForm.value)
      // 如果添加成功重新请求列表
      getPositionList()
      ElMessage.success('添加成功')
    }
    positionDialogVisible.value = false
  } catch (error) {
    console.error('保存职位失败：', error)
    ElMessage.error('保存职位失败')
  }
}

// 组件挂载后获取职位列表
onMounted(() => {
  getPositionList()
})
</script>

<style scoped>
.toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.form-tip {
  margin-left: 8px;
  font-size: 12px;
  color: #909399;
}
</style> 